package apps.sim.core.log;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.logging.Level;
import java.util.logging.LogManager;

import apps.sim.util.Configuration;

public class Logger {
	private final static java.util.logging.Logger logger = java.util.logging.Logger.getAnonymousLogger();
	static {
		try {
			final StringBuilder builder = new StringBuilder();
			builder.append("handlers=java.util.logging.FileHandler");
			builder.append("\n");
			builder.append("java.util.logging.FileHandler.level=ALL");
			builder.append("\n");
			builder.append("java.util.logging.FileHandler.pattern=");
			builder.append(Configuration.CONFIGURATION.get("shycop.log.file", "shycop.log"));
			builder.append("\n");
			builder.append("java.util.logging.FileHandler.formatter=apps.sim.core.log.LogFormatter");
			LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(builder.toString().getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void log(String payload) {
		logger.log(Level.INFO, payload);
	}

	private static File getFile() {
		return new File(Configuration.CONFIGURATION.get("shycop.log.file", "shycop.log"));
	}

	public static String tail(int lines) throws Exception {
		final File file = getFile();
		RandomAccessFile fileHandler = null;
		try {
			fileHandler = new RandomAccessFile(file, "r");
			long fileLength = file.length() - 1;
			StringBuilder sb = new StringBuilder();
			int line = 0;

			for (long filePointer = fileLength; filePointer != -1; filePointer--) {
				fileHandler.seek(filePointer);
				int readByte = fileHandler.readByte();
				if (readByte == 10) {
					line = line + 1;
					if (line == lines) {
						if (filePointer == fileLength) {
							continue;
						} else {
							break;
						}
					}
				} else if (readByte == 13) {
					line = line + 1;
					if (line == lines) {
						if (filePointer == fileLength - 1) {
							continue;
						} else {
							break;
						}
					}
				}
				sb.append((char) readByte);

			}
			// sb.deleteCharAt(sb.length() - 1);

			return sb.reverse().toString();
		} catch (FileNotFoundException e) {
			throw new Exception("Log file not created yet.");
		} finally {
			try {
				fileHandler.close();
			} catch (Exception e) {
				// eat
			}
		}
	}
}
